package com.elinkway.infinitemovies.async;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.UIs;
import com.lvideo.http.bean.LVideoBaseBean;
import com.lvideo.http.bean.LVideoDataHull;

/**
 * 网络请求的异步任务
 */
public abstract class MoviesHttpAsyncTask<T extends LVideoBaseBean> extends
        MoviesBaseTaskImpl implements MoviesHttpAsyncTaskInterface<T> {

    protected Context context;

    private Handler handler;

    private boolean isLocalSucceed = false;

    private String message;

    private static Toast mToast = null;

    public MoviesHttpAsyncTask(Context context) {
        this.context = context;
        handler = new Handler(Looper.getMainLooper());
    }

    @Override
    public final boolean run() {
        try {
            if (!isCancel) {// 加载本地数据
                final T t = loadLocalData();

                if (t != null) {
                    isLocalSucceed = true;
                    postUI(new Runnable() {

                        @Override
                        public void run() {
                            loadLocalDataComplete(t);
                        }
                    });

                }
            }

            boolean hasNet = UIs.hasNet();

            if (!hasNet) {// 判断网络
                cancel();
                postUI(new Runnable() {

                    @Override
                    public void run() {
                        if (!isLocalSucceed) {
                            netNull();
                        }
                    }
                });

                return true;
            }

            if (!isCancel) {// 加载网络数据
                final LVideoDataHull<T> dataHull = doInBackground();

                if (!isCancel) {
                    postUI(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                isCancel = true;
//                                LogUtils.e("PlayMediaController", "isLocalSucceed is " + isLocalSucceed);
                                if (dataHull == null) {
                                    if (!isLocalSucceed) {
                                        LogUtils.e("PlayMediaController", "dataHull is null");
                                        netErr(0, null);
                                    }
                                } else {
                                    int dataType = dataHull.getDataType();
//                                    LogUtils.e("PlayMediaController", "result sourceData is " + dataHull.getSourceData());
                                    LogUtils.e("PlayMediaController", "result dataEntity is " + dataHull.getDataEntity());
                                    LogUtils.e("PlayMediaController", "dataType is " + dataType);
                                    LogUtils.e("PlayMediaController", "result status is " + getRequestResultStatus(dataType));
                                    message = dataHull.getMessage();
                                    boolean isJiexiApi = MoviesHttpApi.APIJIEXI_TAG_1001 == dataHull.getUpdataId();
                                    boolean isHttpException = false;
                                    if(!TextUtils.isEmpty(dataHull.getmHttpCode()) && !"200".equals(dataHull.getmHttpCode())){
                                        isHttpException = true;
                                    }
                                    boolean isNeedSpecialHandle = (isHttpException && isJiexiApi) ||
                                            (isJiexiApi && ("503".equals(dataHull.getCode()) || "211".equals(dataHull.getCode()) || "212".equals(dataHull.getCode())));
                                    if(isNeedSpecialHandle){
                                        if(isHttpException){
                                            codeErr(dataHull.getmHttpCode(), dataHull.getMsg());
                                        }else{
                                            codeErr(dataHull.getCode(), dataHull.getMsg());
                                        }
                                    }else{
                                        if (dataHull.getDataType() == LVideoDataHull.DataType.DATA_IS_INTEGRITY) {
                                            if(!TextUtils.isEmpty(dataHull.getCode()) && !"200".equals(dataHull.getCode())){
                                                codeErr(dataHull.getCode(), dataHull.getMsg());
                                            }else{
                                                onPostExecute(dataHull.getUpdataId(),
                                                        dataHull.getDataEntity());
                                            }
                                        } else if (dataHull.getDataType() == LVideoDataHull.DataType.DATA_CAN_NOT_PARSE) {
                                            if (!isLocalSucceed)
                                                if(isJiexiApi){
                                                    dataNull(dataHull.getUpdataId(), dataHull.getSourceData());
                                                }else{
                                                    dataNull(dataHull.getUpdataId(), message);
                                                }
                                        } else if (dataHull.getDataType() == LVideoDataHull.DataType.DATA_NO_UPDATE) {
                                            if (!isLocalSucceed)
                                                noUpdate();
                                        } else {
                                            if (!isLocalSucceed) {
                                                LogUtils.e("PlayMediaController", "message is " + message);
                                                if(isJiexiApi){
                                                    dataNull(dataHull.getUpdataId(), dataHull.getSourceData());
                                                }else{
                                                    netErr(dataHull.getUpdataId(), message);
                                                }
                                            }
                                        }
                                    }
                                }
                                cancel();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            postUI(new Runnable() {

                @Override
                public void run() {
                    try {
                        LogUtils.e("PlayMediaController", "catch exception");
                        netErr(0, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        return true;
    }

    @Override
    public boolean onPreExecute() {
        return true;
    }

    private void postUI(Runnable runnable) {
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            handler.post(runnable);
        } else {
            runnable.run();
        }
    }

    public String getMessage() {
        return message;
    }

    public final void start() {
        isCancel = !onPreExecute();
        if (isCancel) {
            postUI(new Runnable() {

                @Override
                public void run() {
                    preFail();
                }
            });
        }
        mThreadPool.addNewTask(this);// 加入线程队列，等待执行
    }

    /**
     * 请求前，准备失败回调
     */
    public void preFail() {
    }

    /**
     * 没有网络，回调
     */
    public void netNull() {
    }

    ;

    /**
     * 网络异常和数据错误，回调
     */
    public void netErr(int updateId, String errMsg) {
    };

    /**
     * code码返回不是200
     */
    public void codeErr(String code, String msg){
    };

    /**
     * 数据为空，回调
     */
    public void dataNull(int updateId, String errMsg) {
    }

    ;

    /**
     * 数据无更新，回调
     */
    public void noUpdate() {
    }

    /**
     * 加载本地内容
     */
    public T loadLocalData() {
        return null;
    }

    /**
     * 加载本地内容完成后，回调
     */
    public boolean loadLocalDataComplete(T t) {
        return false;
    }

    /**
     * 本地数据是否加载成功
     */
    public boolean isLocalSucceed() {
        return isLocalSucceed;
    }

    private String getRequestResultStatus(int dataType) {
        String status = "未知原因 and dataType is " + dataType;
        if (0x103 == dataType)
            status = "数据完整";
        if (0x107 == dataType)
            status = "数据不符合解析头文件判断";
        if (0x109 == dataType)
            status = "接口数据无更新";
        if (0x102 == dataType)
            status = "连接失败";
        return status;
    }

    private void showTipsMsgToast(String msg){
        if(mToast == null){
            mToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        }else{
            mToast.setText(msg);
        }
        mToast.show();
    }
}
